<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="z"
          :data="tableData"
          stripe
          border
          :height="tableHeight"

          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" />
          <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" />
          <el-table-column label="操作" align="center" fixed="right" width="320">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status=='0' || scope.row.status=='2'"
                v-hasPermi="['plan:product:edit']"
                type="text"
                @click.stop="edit(scope.row)"
              >编辑</el-button>
              <span v-else class="el-button--text button_grey">编辑</span>
              <el-button
                v-if="scope.row.status=='0' || scope.row.status=='2'"
                v-hasPermi="['plan:product:delete']"
                type="text"
                @click.stop="deleteOne(scope.row)"
              >删除</el-button>
              <span v-else class="el-button--text button_grey">删除</span>
              <el-button
                v-if="scope.row.status=='1'"
                v-hasPermi="['plan:product:cancel']"
                type="text"
                @click.stop="cancel(scope.row)"
              >撤销</el-button>
              <span v-else class="el-button--text button_grey">撤销</span>
              <!-- <el-button
                v-if="scope.row.status !='3'"
                v-hasPermi="['plan:product:finish']"
                type="text"
                @click.stop="finish(scope.row)"
              >报工</el-button>
              <span v-else class="el-button--text button_grey">报工</span> -->
              <el-button
                v-if="(scope.row.canFinish =='1' && (scope.row.status !='0' && scope.row.status !='2')) || scope.row.status=='3'"
                v-hasPermi="['plan:product:finish']"
                type="text"
                @click.stop="finish(scope.row)"
              >完成</el-button>
              <span v-else class="el-button--text button_grey">完成</span>
              <el-button
                v-if="scope.row.canExpiry =='1' && scope.row.status !='0' && scope.row.status !='2'"
                v-hasPermi="['plan:product:termination']"
                type="text"
                @click.stop="termination(scope.row)"
              >终止</el-button>
              <span v-else class="el-button--text button_grey">终止</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>

  </div>
</template>

<script>
import { list, remove, getInfo, addOrUpdate, repealDeliver, expiry, finish, exportForProduct } from '@/api/planManagement/planProductionOrder'
import AddOrUpdate from './addOrUpdate'
import { getDictSelects } from '@/api/common/common'
import ShowDetail from './ShowDetailTitle.vue' // 查看页面
import { getBlob } from '@/utils/util'
export default {
  name: 'Index',
  data() {
    return {
      isManyhead: true,
      loading: true,
      pageExportId: '生产计划单导出',
      pageId: '生产计划单', // 页面唯一标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      // tableKey: 1,
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'statusName', label: '状态', canOrder: false, width: '100' },
        { prop: 'code', label: '计划单号' },
        { prop: 'saleOrderCode', label: '销售订单' },
        { prop: 'planTypeLabel', label: '计划类型', canOrder: false },
        { prop: 'planPersonName', label: '计划人员', canOrder: false },
        { prop: 'planTime', label: '计划日期' },
        { prop: 'remark', label: '备注', canOrder: false }

      ],
      exportTableColumns: [
        { prop: 'statusName', label: '状态', canOrder: false, width: '100' },
        { prop: 'code', label: '计划单号' },
        { prop: 'saleOrderCode', label: '销售订单' },
        { prop: 'planTypeLabel', label: '计划类型', canOrder: false },
        { prop: 'planPersonName', label: '计划人员', canOrder: false },
        { prop: 'planTime', label: '计划日期' },
        { prop: 'remark', label: '备注', canOrder: false }
      ],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'code', label: '计划单号', type: 'input' },
        { prop: 'saleOrderCode', label: '销售订单', type: 'input' },
        { prop: 'planTypeCode', label: '计划类型', type: 'select', optionsName: 'statusTypeOptions' },
        { prop: 'planPersonName', label: '计划人员', type: 'input' },
        { prop: 'status', label: '状态', type: 'select', optionsName: 'statusOptions' },
        { prop: 'planTime', label: '计划日期', type: 'time' }
      ],
      operationData: [ // 右上角的操作按钮
        { label: '新增', perm: 'plan:product:add' },
        { label: '批量删除', perm: 'plan:product:delete' },
        { label: '打印', perm: 'plan:product:list' },
        { label: '批量导出', perm: 'plan:product:export' },
        { label: '页面配置', perm: '' }
      ],
      defaultExport: [],
      statusOptions: [ // 选择组件数据源
        { value: undefined, label: '全部' },
        { value: '0', label: '待提交' },
        { value: '1', label: '已提交' },
        { value: '2', label: '已撤销' },
        { value: '3', label: '生产中' },
        { value: '4', label: '已完成' },
        { value: '5', label: '已终止' }
      ],
      statusTypeOptions: [],
      showKey: { // 查看详情的配置（根据配置自动生成查看页面）
        type: 'column_two',
        keys: [
          { type: 'form', name: '计划单号', key: 'code' }, // type: 'form' 表示是普通的表单展示
          { type: 'form', name: '销售订单', key: 'saleOrderCode' },
          { type: 'form', name: '计划类型', key: 'planTypeLabel' },
          { type: 'form', name: '计划人员', key: 'planPersonName' },
          { type: 'form', name: '计划日期', key: 'planTime' }, // length:'double' 表示占两列
          { type: 'Invoices', name: '生产任务单', key: 'enterWarehouseInvoices', length: 'double' },
          { type: 'form', name: '生产模式', key: 'modelName', length: 'double' },
          { type: 'form', name: '备注', key: 'remark', length: 'double' },
          {
            type: 'table', name: '物料明细', key: 'unmergeData', columns: [ // type: 'table' 表示是表格
              { type: 'column', name: '物料编码', key: 'materialCode', minWidth: '140' }, // type: 'form' 表示是普通的表单展示
              { type: 'column', name: '物料名称', key: 'materialName', minWidth: '100' },
              { type: 'column', name: '规格型号', key: 'materialModel', minWidth: '100' },
              { type: 'column', name: '物料分类', key: 'materialTypeName', minWidth: '100' },
              { type: 'column', name: '物料单位', key: 'materialUnitName', minWidth: '80' },
              { type: 'column', name: '工艺版本号', key: 'engineeringRequirementVersionCode', minWidth: '100' },
              { type: 'column', name: '客户交期', key: 'saleCustomerDeliveryTime', minWidth: '110' },
              { type: 'column', name: '订单数量', key: 'orderNumber', minWidth: '100' },
              { type: 'column', name: '库存数量', key: 'materialInventory', minWidth: '100' },
              { type: 'column', name: '计划数量', fixed: 'right', key: 'planNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '计划交期', key: 'planDealTime', minWidth: '110' },
              { type: 'column', name: '备注', key: 'remark', minWidth: '120' }
            ]
          },
          {
            type: 'table', name: '', key: 'productionTaskListVos', columns: [ // type: 'table' 表示是表格
              { type: 'column', name: '任务单号', key: 'code', minWidth: '120' }, // type: 'form' 表示是普通的表单展示
              { type: 'column', name: '任务类型', key: 'taskTypeName', minWidth: '100' }, // type: 'form' 表示是普通的表单展示

              { type: 'column', name: '物料编码', key: 'materialCode', minWidth: '120' },
              { type: 'column', name: '物料名称', key: 'materialName', minWidth: '100' },
              { type: 'column', name: '规格型号', key: 'materialModel', minWidth: '100' },
              { type: 'column', name: '工序', key: 'engineeringProcessName', minWidth: '100' },
              { type: 'column', name: '是否外协', key: 'productBySelfName', minWidth: '80' },
              { type: 'column', name: '计划数量', key: 'productNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '完成数量', key: 'finishNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '合格数量', key: 'qualifiedTotalNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '不合格数量', key: 'unqualifiedNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '进度', key: 'rateOfProgress', minWidth: '80' },
              { type: 'operate', name: '操作', key: 'schedule', minWidth: '60' }

            ]
          }
        ]
      },
      showKey1: { // 查看详情的配置（根据配置自动生成查看页面）
        type: 'column_two',
        keys: [
          { type: 'form', name: '计划单号', key: 'code' }, // type: 'form' 表示是普通的表单展示
          { type: 'form', name: '销售订单', key: 'saleOrderCode' },
          { type: 'form', name: '计划类型', key: 'planTypeLabel' },
          { type: 'form', name: '计划人员', key: 'planPersonName' },
          { type: 'form', name: '计划日期', key: 'planTime' }, // length:'double' 表示占两列
          { type: 'Invoices', name: '生产任务单', key: 'enterWarehouseInvoices', length: 'double' },
          { type: 'form', name: '生产模式', key: 'modelName', length: 'double' },
          { type: 'form', name: '备注', key: 'remark', length: 'double' },
          {
            type: 'table', name: '物料明细', key: 'unmergeData', columns: [ // type: 'table' 表示是表格
              { type: 'column', name: '物料编码', key: 'materialCode', minWidth: '140' }, // type: 'form' 表示是普通的表单展示
              { type: 'column', name: '物料名称', key: 'materialName', minWidth: '100' },
              { type: 'column', name: '规格型号', key: 'materialModel', minWidth: '100' },
              { type: 'column', name: '物料分类', key: 'materialTypeName', minWidth: '100' },
              { type: 'column', name: '物料单位', key: 'materialUnitName', minWidth: '80' },
              { type: 'column', name: 'BOM版本号', key: 'engineeringBomVersion', minWidth: '100' },
              { type: 'column', name: '工艺路线', key: 'engineeringPathCode', minWidth: '120' },
              { type: 'column', name: '工艺路线版本号', key: 'engineeringPathVersion', minWidth: '120' },
              { type: 'column', name: '客户交期', key: 'saleCustomerDeliveryTime', minWidth: '110' },
              { type: 'column', name: '订单数量', key: 'orderNumber', minWidth: '100' },
              { type: 'column', name: '库存数量', key: 'materialInventory', minWidth: '100' },
              { type: 'column', name: '计划数量', fixed: 'right', key: 'planNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '计划交期', key: 'planDealTime', minWidth: '110' },
              { type: 'column', name: '备注', key: 'remark', minWidth: '120' }
            ]
          },
          {
            type: 'table', name: '', key: 'productionTaskListVos', columns: [ // type: 'table' 表示是表格
              { type: 'column', name: '任务单号', key: 'code', minWidth: '120' }, // type: 'form' 表示是普通的表单展示
              { type: 'column', name: '任务类型', key: 'taskTypeName', minWidth: '100' }, // type: 'form' 表示是普通的表单展示

              { type: 'column', name: '物料编码', key: 'materialCode', minWidth: '120' },
              { type: 'column', name: '物料名称', key: 'materialName', minWidth: '100' },
              { type: 'column', name: '规格型号', key: 'materialModel', minWidth: '100' },
              { type: 'column', name: '工序', key: 'engineeringProcessName', minWidth: '100' },
              { type: 'column', name: '是否外协', key: 'productBySelfName', minWidth: '80' },
              { type: 'column', name: '计划数量', key: 'productNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '完成数量', key: 'finishNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '合格数量', key: 'qualifiedTotalNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '不合格数量', key: 'unqualifiedNumber', Width: this.SETTINGS.settings_decimalDigits_length },
              { type: 'column', name: '进度', key: 'rateOfProgress', minWidth: '80' },
              { type: 'operate', name: '操作', key: 'schedule', minWidth: '60' }

            ]
          }
        ]
      }
    }
  },
  created() {
    this.getDictOptions()
  },
  mounted() {
  },
  methods: {
    getExportData(data) {
      if (this.selectionsAll.length == 0) {
        this.$message.warning('请选择单据')
        return
      }
      if (this.selectionsAll.filter(item => item.status == '0' || item.status == '2').length > 0) {
        this.$message.warning('存在待提交和已撤销的单据，无法导出，请重新选择单据')
        this.$parent.selectionsAll = []
        return
      }
      return getBlob('/plan/production/exportForProduct', data, 'post')
    },
    getDictOptions() {
      getDictSelects('planTypeCode').then(res => {
        res.data.forEach(item => {
          item['value'] = item.dictCode
          item['label'] = item.dictLabel
        })
        this.statusTypeOptions = res.data
      })
    },
    cellStyle({ row, column }) {
      if (column.property == 'code') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'code':
          this.showDetail(row)
          break
      }
    },
    showDetail(row) {
      console.log(row)
      let showKey = this.showKey
      getInfo(row[this.mainId]).then(res => {
        res.data.unmergeData = this.sumArr(res.data.unmergeData)
        // 计算合格数量
        res.data.productionTaskListVos.map((item) => {
          item.finishNumber = item.reportTotalNumber * 1 + item.badnessTotalNumber * 1
          item.unqualifiedNumber = item.disqualifiedTotalNumber * 1 + item.badnessTotalNumber * 1
          item.schedule = parseFloat((item.qualifiedTotalNumber * 100 / item.productNumber).toFixed(2)) + '%'
        })
        res.data.modelName = res.data.model == '1' ? '按BOM和工艺路线' : '按工艺要求'

        if (res.data.model == '1') {
          showKey = this.showKey1
        }
        console.log(res.data)
        this.$layer.iframe({// 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              showKey: showKey
            }// props
          },
          area: ['9999px', '9999px'],
          title: '查看生产计划单', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
    },
    // 合并数据展示
    sumArr(arrList) {
      const nameArr = [...new Set(arrList.map(i => i.materialId))]// 名称集合
      const list = []
      nameArr.forEach(v => {
        const filterlist = arrList.filter(a => v == a.materialId)
        list.push(filterlist)
      })
      const outArr = []
      list.forEach((item, index) => {
        // if (!this.formData.id) {
        //   if (item.length > 1) {
        //     var min = Math.min.apply(Math, item.map(o => o.saleCustomerDeliveryTimeNumber))
        //     item[0].saleCustomerDeliveryTime = new Date(min).toLocaleDateString().slice().replace(/\//g, '-')
        //   }
        //   item[0].planDealTime = item[0].saleCustomerDeliveryTime
        // }
        // 新增第一次合并计算未发数量，否则计算计划数量
        // if (this.fristFalg) {
        //   // 合计订单数量
        //   const orderNumber = item.reduce((total, g) => {
        //     return total + Number(g.orderNumber)
        //   }, 0)
        //   const planNumber = item.reduce((total, g) => {
        //     return total + Number(g.willDeliverNumber)
        //   }, 0)
        //   outArr.push({
        //     ...item[0],
        //     orderNumber: orderNumber,
        //     planNumber: planNumber
        //   })
        // } else {
        // 合计订单数量
        const orderNumber = item.reduce((total, g) => {
          return total + Number(g.orderNumber)
        }, 0)
        const planNumber = item.reduce((total, g) => {
          return total + Number(g.planNumber)
        }, 0)
        // 如果订单数量合计为0则置空
        if (orderNumber == 0) {
          outArr.push({
            ...item[0],
            orderNumber: '',
            planNumber: planNumber
          })
        } else {
          outArr.push({
            ...item[0],
            orderNumber: orderNumber,
            planNumber: planNumber
          })
        }
        // }
      })
      return outArr
    },
    refresh() {
      this.pageData.pageNum = 1
      this.getList()
    },
    refresh2() {
      this.tableData = []
      setTimeout(() => {
        this.getList()
      }, 50)
    },
    getList() {
      list(this.pageData).then(res => {
        res.data.map((item) => {
          if (item.status == 0 || item.status == 2) {
            item.canDelete = 1
          } else {
            item.canDelete = 0
          }
        })
        this.tableData = res.data
        this.total = res.total
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
          this.$refs['table'].doLayout()
        })
      })
    },
    add() {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['1320px', '700px'],
        title: '新增生产计划单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    edit(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          }// props
        },
        area: ['1320px', '700px'],
        title: '编辑生产计划单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    finish(row) {
      const _this = this
      this.$confirm('确定要完成吗', '完成确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        finish(row.id).then(res2 => {
          _this.$message({
            message: res2.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch(() => {})
      // getInfo(row.id).then(res => {
      // })
    },
    termination(row) {
      const _this = this
      this.$confirm('确定要终止吗', '终止确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        expiry(row.id).then(res2 => {
          _this.$message({
            message: res2.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch(() => {})
      // getInfo(row.id).then(res => {
      // })
    },
    // 撤销弹框
    cancel(row) {
      this.tableRemokeColum = row
      const confirmText = ['是否确认撤销该单据？']
      const confirmText2 = ['关联的生产任务单、外协订单也将删除。']
      const newDatas = []
      const h = this.$createElement
      newDatas.push(h('i', { class: 'el-icon-warning', style: 'color:#ffba00;font-size:24px;margin-right:12px;vertical-align: -4px' }))
      for (const i in confirmText) {
        newDatas.push(h('span', null, confirmText[i]))
      }
      for (const i in confirmText2) {
        newDatas.push(h('p', { style: 'color: rgba(74, 70, 70, 0.4);margin-left:36px' }, confirmText2[i]))
      }
      this.$confirm('撤销确认', {
        title: '撤销确认',
        message: h('div', null, newDatas),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'cancelConfirm'
      })
        .then(() => {
          const _this = this
          repealDeliver(_this.tableRemokeColum.id).then(res => {
            _this.$message({
              message: res.msg,
              type: 'success'
            })
            _this.selectionsAll = []
            _this.dialogRevoke = false
            _this.getList()
            _this.tableRemokeColum = {}
          })
          // 点击“确定”按钮后执行的方法
        })
        .catch(() => {
          this.dialogRevoke = false
          // 点击“关闭”按钮后执行的方法
        })
      // this.dialogRevoke = true;
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove(row[_this.mainId]).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.selectionsAll = []
          _this.getList()
        })
      }).catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove(deleteIds)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
